<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数!"
        :closable="false"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            clearable
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button
                size="mini"
                type="primary"
                :disabled="selectedCateKeys.length !== 3"
                @click="addDialogVisible = true"
                >添加参数</el-button
              >
            </el-col>
          </el-row>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand" label="">
              <template slot-scope="scope">
                <el-row>
                  <el-col>
                    <el-input
                      size="mini"
                      v-model="inputValue"
                      clearable
                      :placeholder="`请输入${titleText}值`"
                      style="width:150px;margin:0 15px 15px 0"
                    ></el-input>
                    <el-button
                      type="primary"
                      size="mini"
                      @click="handleInputConfirm(scope.row)"
                      >添加{{ titleText }}值</el-button
                    >
                  </el-col>
                </el-row>
                <el-tag
                  closable
                  v-for="(v, i) of scope.row.attr_vals"
                  :key="v"
                  @close="handleClose(scope.row, i)"
                >
                  {{ v }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                ><el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col>
              <el-button
                size="mini"
                type="primary"
                :disabled="selectedCateKeys.length !== 3"
                @click="addDialogVisible = true"
                >添加属性</el-button
              >
            </el-col>
          </el-row>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand" label="">
              <template slot-scope="scope">
                <el-row>
                  <el-col>
                    <el-input
                      size="mini"
                      v-model="inputValue"
                      clearable
                      :placeholder="`请输入${titleText}值`"
                      style="width:150px;margin:0 15px 15px 0"
                    ></el-input>
                    <el-button
                      type="primary"
                      size="mini"
                      @click="handleInputConfirm(scope.row)"
                      >添加{{ titleText }}值</el-button
                    >
                  </el-col>
                </el-row>
                <el-tag
                  closable
                  v-for="(v, i) of scope.row.attr_vals"
                  :key="v"
                  @close="handleClose(scope.row, i)"
                >
                  {{ v }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                ><el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import message from '../../utils/message'
export default {
  name: 'Params',
  data() {
    return {
      cateList: [],
      selectedCateKeys: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      inputValue: ''
    }
  },
  methods: {
    async getCateList() {
      let res = await this.$http.get('categories')
      if (res.meta.status === 200) {
        this.cateList = res.data
      } else {
        message('error', '获取商品失败!')
        return false
      }
    },
    handleChange() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      this.getParamsData()
    },
    handleTabClick() {
      this.getParamsData()
    },
    async getParamsData() {
      let res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      console.log(res)
      if (res.meta.status === 200) {
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
        res.data.forEach(v => {
          v.attr_vals = v.attr_vals ? v.attr_vals.split(' ') : []
        })
        message('success', '获取分类参数列表成功!')
      } else {
        message('error', '获取分类参数列表失败!')
        return false
      }
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          let res = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
          )
          if (res.meta.status === 201) {
            this.addDialogVisible = false
            this.getParamsData()
            message('success', `添加${this.titleText}成功!`)
          } else {
            message('error', `添加${this.titleText}失败!`)
            return false
          }
        } else {
          return false
        }
      })
    },
    async showEditDialog(attr_id) {
      this.editDialogVisible = true
      let res = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status === 200) {
        this.editForm = res.data
        message('success', `查询${this.titleText}成功!`)
      } else {
        message('error', `查询${this.titleText}失败!`)
        return false
      }
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          let res = await this.$http.put(
            `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName
            }
          )
          if (res.meta.status === 200) {
            this.editDialogVisible = false
            this.getParamsData()
            message('success', `编辑提交${this.titleText}成功!`)
          } else {
            message('error', `编辑提交${this.titleText}失败!`)
            return false
          }
        } else {
          return false
        }
      })
    },
    async removeParams(attr_id) {
      let confirmResult = await this.$confirm(
        `此操作将永久删除该${this.titleText}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmResult === 'confirm') {
        let res = await this.$http.delete(
          `categories/${this.cateId}/attributes/${attr_id}`
        )
        if (res.meta.status === 200) {
          this.getParamsData()
          message('success', `删除${this.titleText}成功!`)
        } else {
          message('error', `删除${this.titleText}失败!`)
          return false
        }
      } else {
        message('info', `已取消了删除!`)
        return false
      }
    },
    async saveAttrVals(row) {
      let res = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status === 200) {
        message('success', '修改参数成功!')
      } else {
        message('error', '修改参数失败!')
        return false
      }
    },
    handleInputConfirm(row) {
      if (this.inputValue.trim()) {
        row.attr_vals.push(this.inputValue)
        this.saveAttrVals(row)
        this.inputValue = ''
      } else {
        this.inputValue = ''
        return false
      }
    },
    handleClose(row, index) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[this.selectedCateKeys.length - 1]
      } else {
        return null
      }
    },
    titleText() {
      if (this.activeName === 'many') {
        return '参数'
      } else {
        return '属性'
      }
    }
  },
  mounted() {
    this.getCateList()
  }
}
</script>

<style scoped lang="less">
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  margin-left: 15px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 150px;
}
</style>
